package com.yuan.web.servlet;

import com.yuan.pojo.User;
import com.yuan.utils.DruidUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.dbutils.QueryRunner;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.Map;

@WebServlet("/register")
public class ServletRegister extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        Map<String, String[]> parameterMap = request.getParameterMap();
        User user = new User();
        user.setStatus("0");

        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet resultSet = null;
        try {

            BeanUtils.populate(user,parameterMap);
            QueryRunner queryRunner = new QueryRunner(DruidUtil.getDataSource());
            String sql = "insert into user values (null,?,?,?,?,?,?,?)";
            queryRunner.update(sql,user.getUsername(),user.getPassword(),
                    user.getAddress(),user.getNickname(),user.getGender(),user.getEmail());
                response.sendRedirect("login.jsp");
                request.getSession().setAttribute("msg","注册成功");
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("注册失败");
            //如果注册失败，则向浏览器响应一句"注册失败"
        }
    }
}
